import { ScopeEnum } from '@/utils/enum'

/**
 * 小程序权限是否开启
 * @param scopeName
 * @return undefined 未授权-拉起授权面板;  false 拒绝授权-打开权限列表;  true 已授权;
 */
export const getSettingIsOk = (scopeName) => {
  return new Promise((resolve) => {
    uni.getSetting({
      success: (res) => {
        resolve(res.authSetting[`scope.${scopeName}`])
      },
    })
  })
}
/**
 * 小程序权限请求
 * @param scopeName string
 * @param successCallback function
 * @param failCallback function
 */
export const goAuthorize = (scopeName, successCallback, failCallback) => {
  return new Promise((resolve) => {
    uni.authorize({
      scope: `scope.${scopeName}`,
      success() {
        resolve(true)
        successCallback()
      },
      fail() {
        resolve(false)
        isShowOpenSetting(scopeName, failCallback)
      },
    })
  })
}
/**
 * 拒绝授权后，是否到权限列表页手动开启
 * @param scopeName
 * @param callback function
 */
export const isShowOpenSetting = (scopeName, callback) => {
  uni.showModal({
    title: '温馨提示',
    content: `您未授权${ScopeEnum[scopeName]}权限，功能将无法正常使用，是否开启！`,
    success: (res) => {
      if (res.confirm) {
        console.log('用户点击确定')
        goOpenSetting(scopeName, callback)
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}
/**
 * 打开授权列表
 * @param scopeName
 * @param successCallback
 * @returns
 */
export const goOpenSetting = (scopeName, successCallback) => {
  return new Promise((resolve) => {
    uni.openSetting({
      success(res) {
        if (res.authSetting[`scope.${scopeName}`]) {
          successCallback()
          resolve(true)
        }
      },
      fail(res) {
        // resolve(false)
      },
    })
  })
}
